﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;
using Kazuku.Core.Models;
using NormActiveRecord;

namespace Kazuku.Core {
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class Global : NinjectHttpApplication {

		private static KazukuVirtualPathProvider _pathProvider;
		private static Hashtable _siteTemplates = new Hashtable();

		public static void RegisterRoutes(RouteCollection routes) {
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
			routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

			Route route = routes.MapRoute(
								"Default", // Route name
								"{controller}/{action}/{id}", // URL with parameters
								// TODO: This needs to be the home page of the default org
								new { controller = "Page", action = "Show", id = UrlParameter.Optional } // Parameter defaults
						  );
			route.RouteHandler = new KazukuRouteHandler();
			RouteTable.Routes.RouteExistingFiles = false;
		}

		protected override void OnApplicationStarted() {
			AreaRegistration.RegisterAllAreas();
			RegisterRoutes(RouteTable.Routes);
			//RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);


			IModelFactory model = Container.Get<IModelFactory>();
			IList<DynamicTemplate> dynamicTemplates = model.Get<DynamicTemplate>().All().ToList();
			foreach (DynamicTemplate template in dynamicTemplates) {
				_siteTemplates.Add(template.GetViewPath(), System.Text.Encoding.UTF8.GetBytes(template.Body));
			}
			_pathProvider = new KazukuVirtualPathProvider(_siteTemplates);
			HostingEnvironment.RegisterVirtualPathProvider(_pathProvider);
			//RegisterAllControllersIn(Assembly.GetExecutingAssembly());
			// Get all the assemblies with controllers in them
			
			SetEngines();
		}

		public void AddDynamicTemplateToVirtualPathProvider(DynamicTemplate template) {
			_pathProvider.AddSiteTemplate(template.GetViewPath(), System.Text.Encoding.UTF8.GetBytes(template.Body));
		}

		public void RemoveDynamicTemplateFromVirtualProvider(string viewPath) {
			_pathProvider.RemoveSiteTemplate(viewPath);
		}

		/// <summary>
		/// Set the alternate view engines here
		/// </summary>
		protected void SetEngines() {
			//Spark is lovely
			//and so is nHAML
			//you can enable either Below

			//to disable WebForms view engine...
			//ViewEngines.Engines.Clear();

			/*
			var settings = new SparkSettings()
			 .SetDebug(true)
			 .SetAutomaticEncoding(true)
			 .AddAssembly("Web")
			 .AddNamespace("Web.Model")
			 .AddNamespace("System.Collections.Generic")
			 .AddNamespace("System.Linq")
			 .AddNamespace("System.Web.Mvc")
			 .AddNamespace("System.Web.Mvc.Html");

			ViewEngines.Engines.Add(new SparkViewFactory(settings));
			*/

			//config is in the web.config
			//ViewEngines.Engines.Add(new NHaml.Web.Mvc.NHamlMvcViewEngine());
		}

		protected override IKernel CreateKernel() {
			_container = new StandardKernel(new NinjectBindings());
			return Container;
		}

		protected void Application_End() {
		}

		protected void Application_Error() {
			// Get the exception object.
			Exception ex = Server.GetLastError();
			string msg = ex.Message;
		}
		
		static IKernel _container;
		public static IKernel Container {
			get {
				//if (_container == null) {
				//    _container = new StandardKernel(new NinjectDefaultBindings());
				//}
				return _container;
			}
		}
	}
}